package com.sky.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.utils.EasyExcelUtil;
import com.sky.vo.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName ReportService
 * @Description 报表统计业务实现类
 * @Author sld
 * @Date 2024/7/16 9:06
 * Version 1.0
 **/
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        // 获得时间区间内的日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 生成每一天的日期
        while (!begin.equals(end)){
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }
        // 根据每一天的日期遍历查询
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 添加当天的开始时间和结束时间，如：2024-07-01 00:00:00.000  2024-07-01 23:59:59.999
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 封装查询参数
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);    // 只查询订单完成的
            map.put("begin",beginTime);
            map.put("end", endTime);
            // 查询数据库获取当前的营业额
            Double turnover = reportMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;   // 空值赋值为0
            turnoverList.add(turnover);
        }

        //数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))   // list转String
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 根据时间区间统计用户数量
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 获得时间区间内的日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 遍历生成每一天的日期
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 结果列表
        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数
        // 遍历日期集合，查询每天的用户数量
        for (LocalDate date : dateList) {
            // 添加当天的开始时间和结束时间，如：2024-07-01 00:00:00.000  2024-07-01 23:59:59.999
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            Integer newUser = reportMapper.getUserCount(beginTime, endTime);
            //总用户数量 select count(id) from user where  create_time < ?
            Integer totalUser = reportMapper.getUserCount(null, endTime);
            // 添加到结果列表
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        // 数据封装
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 根据时间区间统计订单数量
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end){
        // 获得时间区间内的日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 遍历生成每一天的日期
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 添加当天的开始时间和结束时间，如：2024-07-01 00:00:00.000  2024-07-01 23:59:59.999
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的总订单数 select count(id) from orders where order_time > ? and order_time < ?
            Integer orderCount = reportMapper.getOrderCount(beginTime, endTime, null);
            //查询每天的有效订单数 select count(id) from orders where order_time > ? and order_time < ? and status = ?
            Integer validOrderCount = reportMapper.getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     * */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end){
        // 添加日期当天的开始时间和结束时间，如：2024-07-01 00:00:00.000  2024-07-01 23:59:59.999
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 查询top10
        List<GoodsSalesDTO> goodsSalesDTOList = reportMapper.getSalesTop10(beginTime, endTime);
        // list转String
        String nameList = StringUtils.join(
                // 遍历goodsSalesDTOList，获取所有name的集合
                goodsSalesDTOList.stream().map(GoodsSalesDTO::getName)
                        .collect(Collectors.toList()),
                ",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");
        // 返回结果
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**导出近30天的运营数据报表
     * @param response
     **/
    @SneakyThrows
    public void exportBusinessData(HttpServletResponse response)  {
        // 查询日期
        LocalDate begin = LocalDate.now().minusDays(30); //前30天
        LocalDate end = LocalDate.now().minusDays(1);   //前1太难
        // 文件名
        String fileName = "导出"+begin + "到" + end + "运营数据002报表";

        // 下载文件设置
        EasyExcelUtil.initResponse(response,fileName);
        // 加载模板文件
        ClassPathResource inputStream = new ClassPathResource("template/运营数据1报表模板.xlsx");
        InputStream templateFile  = inputStream.getInputStream();
        // 响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 创建写入Excel对象
        ExcelWriter writer = EasyExcel.write(outputStream)
                .withTemplate(templateFile)
                .build();
        // 获取工作表对象
        WriteSheet writeSheet = EasyExcel.writerSheet().build();

        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(
                LocalDateTime.of(begin,LocalTime.MIN),
                LocalDateTime.of(end, LocalTime.MAX));
        // 填充概览数据
        writer.fill(businessData,writeSheet);

        // 明显列表
        ArrayList<Object> list = new ArrayList<>();
        end = end.plusDays(1);
        // 获取明细数据
        while ( begin.isBefore(end)){
            BusinessDataVO data = workspaceService.getBusinessData(
                    LocalDateTime.of(begin, LocalTime.MIN),
                    LocalDateTime.of(begin, LocalTime.MAX));
            data.setDate(begin.toString());
            list.add(data);
            begin = begin.plusDays(1);
        }
        // 列表填充配置
        FillConfig.builder().forceNewRow(true).build(); // 自动换行
        // 填充列表
        writer.fill(list,writeSheet);
        writer.finish();    // 填充完成
    }
}